package me.shurufa.fragments;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.finalteam.okhttpfinal.HttpRequest;
import cn.finalteam.toolsfinal.coder.MD5Coder;
import de.greenrobot.event.EventBus;
import me.shurufa.R;
import me.shurufa.activities.NewMainActivity;
import me.shurufa.db.PersistenceUtils;
import me.shurufa.net.API;
import me.shurufa.net.RequestParams;
import me.shurufa.net.okhttp.callback.HttpCallback;
import me.shurufa.response.LoginResp;
import me.shurufa.response.base.BaseResp;
import me.shurufa.utils.Constants;
import me.shurufa.utils.Utils;

/**
 * 在此写用途
 *
 * @FileName: me.shurufa.fragments.RegisterFragment.java
 * @author: kHRYSTAL
 * @email: 723526676@qq.com
 * @date: 2016-01-15 10:03
 */
public class NewRegisterFragment extends BaseFragment implements View.OnClickListener {

    @Bind(R.id.mobile_edit)
    EditText mobileEdit;

    @Bind(R.id.verify_code_edit)
    EditText verifyCodeEdit;

    @Bind(R.id.verify_code_button)
    TextView verifyCodeButton;

    @Bind(R.id.password_edit)
    EditText passwordEdit;

    @Bind(R.id.name_edit)
    EditText nameEdit;

    @Bind(R.id.register_button)
    Button registerButton;

    @Bind(R.id.go_login)
    LinearLayout goLogin;

    @Bind(R.id.iv_enter_not_login)
    LinearLayout iv_enter_not_login;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_new_register, container, false);
        return view;
    }

    @Override
    protected void initUI(View view) {
        super.initUI(view);
        registerButton.setOnClickListener(this);
        goLogin.setOnClickListener(this);
        verifyCodeButton.setOnClickListener(this);
        iv_enter_not_login.setOnClickListener(this);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.register_button:
                if (isInputValid()) {
                    doRegister();
                }
                break;
            case R.id.verify_code_button:

                if (TextUtils.isEmpty(mobileEdit.getText().toString().trim()) || mobileEdit.getText().toString().trim().length() != 11) {
                    Utils.showToast(R.string.input_valid_mobile_number);
                    mobileEdit.requestFocus();
                } else {
                    getVerifyCode();
                }
                break;
            case R.id.go_login:
                EventBus.getDefault().post(new Intent(Constants.ACTION_LOGIN_SWITCH));
                break;
            case R.id.iv_enter_not_login:
                PersistenceUtils.logout();

                Intent intent = new Intent(getActivity(), NewMainActivity.class);
                startActivity(intent);
                getActivity().finish();
                break;
        }
    }

    private boolean isInputValid() {
        String mobile = mobileEdit.getText().toString().trim();
        if (mobile.length() != getResources().getInteger(R.integer.mobile_length)) {
            Utils.showToast(R.string.please_input_mobile_number);
            return false;
        }
        String verifyCode = verifyCodeEdit.getText().toString().trim();
        if (verifyCode.length() != getResources().getInteger(R.integer.verify_code_length)) {
            Utils.showToast(R.string.invalid_verify_code);
            return false;
        }
        String password = passwordEdit.getText().toString().trim();
        if (password.length() < getResources().getInteger(R.integer.min_password_length)) {
            Utils.showToast(R.string.password_too_short);
            return false;
        }
        String nickname = nameEdit.getText().toString().trim();
        if (nickname.length() < getResources().getInteger(R.integer.min_nick_length)) {
            Utils.showToast(R.string.nick_too_short);
            return false;
        }
        if (nickname.length() > getResources().getInteger(R.integer.max_nick_length)) {
            Utils.showToast(R.string.nick_too_long);
            return false;
        }

//        wtf? 设计稿注册不设置昵称
//        String nick = nickEdit.getText().toString().trim();
//        if (nick.length() < getResources().getInteger(R.integer.min_nick_length)) {
//            Utils.showToast(R.string.nick_too_short);
//            return false;
//        }
//        if (nick.length()>getResources().getInteger(R.integer.max_nick_length)){
//            Utils.showToast(R.string.nick_too_long);
//            return false;
//        }
        return true;
    }

    private void doRegister() {

        RequestParams params = new RequestParams();
        params.addFormDataPart("mobile", mobileEdit.getText().toString().trim());
        params.addFormDataPart("password", MD5Coder.getMD5Code(passwordEdit.getText().toString()));
        params.addFormDataPart("captcha", verifyCodeEdit.getText().toString().trim());
        params.addFormDataPart("username", nameEdit.getText().toString().trim());

        HttpRequest.post(API.REGISTER, params, new HttpCallback<LoginResp>() {

            @Override
            public void onRespSuccess(LoginResp loginResp) {
                try {
                    if (loginResp.data == null) {
                        Utils.showToast(R.string.sys_err);
                        return;
                    }
                    Utils.showToast(R.string.register_success);
                    PersistenceUtils.setUser(loginResp.data);
                    Intent intent = new Intent(getActivity(), NewMainActivity.class);
                    startActivity(intent);
                    getActivity().finish();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onRespFailure(LoginResp loginResp) {

            }
        });

    }

    private void getVerifyCode() {
        RequestParams params = new RequestParams();
        params.addFormDataPart("mobile", mobileEdit.getText().toString());
        params.addFormDataPart("send_type", "register");
        HttpRequest.post(API.GET_CAPTCHA, params, new HttpCallback<BaseResp>(getActivity(), getString(R.string.getting_registration_sms)) {
            @Override
            public void onRespSuccess(BaseResp baseResp) {
                try {
                    Utils.showToast(R.string.get_registration_sms_success);
                    mHandler.sendEmptyMessage(MSG_COUNT_DOWN_BEGIN);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onRespFailure(BaseResp baseResp) {
            }
        });
    }

//    倒计时 start
    private static final int MSG_COUNT_DOWN = 30;

    private static final int MSG_COUNT_DOWN_BEGIN = 31;

    private static final int MSG_COUNT_DOWN_FINISHED = 32;

    private int countDown = Constants.SMS_COUNT_DOWN_TIME;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_COUNT_DOWN_BEGIN:
                    verifyCodeButton.setEnabled(false);
                    sendEmptyMessage(MSG_COUNT_DOWN);
                    break;
                case MSG_COUNT_DOWN:
                    countDown--;
                    verifyCodeButton.setText(
                            String.format(getString(R.string.count_down_time_left), countDown));
                    if (countDown > 0) {
                        sendEmptyMessageDelayed(MSG_COUNT_DOWN, 1000);
                    } else {
                        verifyCodeButton.setText(getString(R.string.get_verify_code));
                        verifyCodeButton.setEnabled(true);
                        countDown = Constants.SMS_COUNT_DOWN_TIME;
                    }
                    break;
                case MSG_COUNT_DOWN_FINISHED:
                    break;

            }

        }
    };

    private void finishCountdown() {
        countDown = 0;
        mHandler.removeMessages(MSG_COUNT_DOWN);
    }
//    倒计时 end

    @Override
    public void onDestroy() {
        finishCountdown();
        super.onDestroy();
    }
}
